import { reactive, watch } from 'vue';
import XEClipboard from 'xe-clipboard';
import { formatDate, getDateStr, isNullPm } from '@utils/baseMethods';
import { apiScheduleUpdateSchedulePlanByDate, scheduleScheduleList } from '@/api/url/scheduling';
import { VXETable } from 'vxe-table';
import notification from '@arco-design/web-vue/es/notification';
import { scheduleGetMaterialStatus } from '@/api/url/BOMdetails';

export default function importConfig() {
  const base = reactive<any>({
    tableRef: null,
    tableData: null,
    pagination: {
      current: 1,
      pageSize: 10,
      total: 100,
    },
    checkFrom: null,
    productionScheduleStatusList: [],
    productionScheduleSumGroupbyDateVoList: [],
    proDateVoList: [],
    interval: 20,
    timeInterval: [],
  });

  const getTableData = () => {
    const steam = {
      pageNum: base.pagination.current,
      pageSize: base.pagination.pageSize,
      custom: base.checkFrom?.custom,
      endTime: base.checkFrom?.endTime?.replace(/\-/g, ''),
      lineType: base.checkFrom?.lineType,
      orderId: base.checkFrom?.orderId,
      productIdStart: base.checkFrom?.productIdStart,
      productSpecifications: base.checkFrom?.productSpecifications,
      scheduled: true,
      startTime: base.checkFrom?.startTime?.replace(/\-/g, ''),
      unScheduled: true,
      workCenter: base.checkFrom?.workCenter,
      workersNumber: base.checkFrom?.workersNumber,
    };
    scheduleScheduleList(steam).then((res) => {
      if (isNullPm(base.getDate)) base.tableData = [];
      base.tableData = res.data.list.records;
      base.pagination.total = res.data.list.total;
      base.productionScheduleStatusList = res.data.productionScheduleStatusList;
      base.productionScheduleSumGroupbyDateVoList = res.data.productionScheduleSumGroupbyDateVoList;
      base.productionScheduleSumGroupbyDateVoList.map((reb: any) => {
        const steam = reb.date.substring(4, 6) + '-' + reb.date.substring(6, 8);
        reb.key = steam;
        base.proDateVoList.push(steam);
      });
      console.log(base.productionScheduleSumGroupbyDateVoList, '====> base.productionScheduleSumGroupbyDateVoList');
      timeLoader();
      dataLoading();
    });
  };

  /**
   * @example 默认的全局导出方法
   */
  const init = () => {
    getTableData();
  };

  /**
   * @exports dataLoading 已排数量数据导入方法
   */
  const dataLoading = () => {
    base.productionScheduleStatusList.map((res: any) => {
      base.tableData.map((reb: any) => {
        if (reb.workOrderType == res.workersId && reb.workersNumber == res.workersNumber) {
          const steam = res.date.substring(4, 6) + '-' + res.date.substring(6, 8);
          if (!isNullPm(reb[steam])) reb[steam].value = res.nums;
        }
      });
    });
  };

  /**
   * @exports menuConfig 表单配置器
   */
  const menuConfig = reactive<any>({
    className: 'my-menus',
    header: {
      options: [[{ code: 'exportAll', name: '导出所有.csv' }]],
    },
    body: {
      options: [
        [
          { code: 'copy', name: '复制', prefixIcon: 'vxe-icon-copy', className: 'my-copy-item' },
          { code: 'checkBom', name: '查看工艺路线', prefixIcon: 'vxe-icon-menu', className: 'my-copy-item' },
          { code: 'checkMateriel', name: '查看物料情况', prefixIcon: 'vxe-icon-chart-pie', className: 'my-copy-item' },
        ],
      ],
    },
    footer: {
      options: [[{ code: 'clearAll', name: '清空数据' }]],
    },
  });

  /**
   * @exports timeLoader 时间载入器
   */
  const timeLoader = () => {
    const steam = timeGenerator();
    const listCopy: any = [];
    base.tableData.map((res: any) => {
      listCopy.push({
        ...res,
        ...steam,
      });
    });
    base.tableData = JSON.parse(JSON.stringify(listCopy));
  };
  /**
   * @exports timeGenerator 时间生成器
   */
  const timeGenerator = () => {
    const steam = {};
    base.timeInterval = [];
    const nowTime = formatDate(new Date(), 'yyyy-MM-dd');
    for (let a = 1; a <= base.interval; a++) {
      const timeTitle = getDateStr(nowTime, a);
      base.timeInterval.push(formatDate(new Date(timeTitle), 'MM-dd'));
      steam[formatDate(new Date(timeTitle), 'MM-dd')] = {
        value: null,
        key: formatDate(new Date(timeTitle), 'yyyyMMdd'),
        labelKey: timeTitle,
      };
    }
    return steam;
  };

  /**
   * @exports contextMenuClickEvent 表单操作格式
   * @param param0
   */
  const contextMenuClickEvent = ({ menu, row, column }) => {
    switch (menu.code) {
      case 'copy':
        // 示例
        if (row && column) {
          if (XEClipboard.copy(row[column.field])) {
            VXETable.modal.message({ content: '已复制到剪贴板！', status: 'success' });
          }
        }
        break;
      case 'checkBom':
        viewOptionDetails(row.workOrderType, row.workersNumber, row.process, row[column.field].value);
        break;
      default:
        console.log(`点击了 ${menu.name} 选项`, row, column, row[column.field]);
    }
  };

  const meanNum = (list, field) => {
    let count = 0;
    list.forEach((item) => {
      count += Number(item[field]);
    });
    return count / list.length;
  };

  /**
   * @exports footerMethod 底部展示栏
   * @param param0
   * @returns
   */
  const footerMethod = ({ columns, data }) => {
    return [
      columns.map((column, columnIndex) => {
        if (columnIndex === 0) {
          return '平均';
        }
        if (base.proDateVoList.includes(column.field)) {
          let steam = null;
          for (let a = 0; a < base.productionScheduleSumGroupbyDateVoList.length - 1; a++) {
            if (base.productionScheduleSumGroupbyDateVoList[a].key == column.field) {
              steam = base.productionScheduleSumGroupbyDateVoList[a].nums;
              break;
            } else steam = null;
          }
          return steam;
        }
        return null;
      }),
    ];
  };

  const selectAllChangeEvent = ({ checked }) => {
    const $table = base.tableRef;
    if ($table) {
      const records = $table.getCheckboxRecords();
      console.log(checked ? '所有勾选事件' : '所有取消事件', records);
    }
  };
  const selectChangeEvent = ({ checked }) => {
    const $table = base.tableRef;
    if ($table) {
      const records = $table.getCheckboxRecords();
      console.log(checked ? '勾选事件' : '取消事件', records);
    }
  };

  const inputTion = (param, row, value, rowIndex) => {
    debouncedFunction(param, row, value, rowIndex);
  };

  /**
   * @exports debounce 防抖代码
   * @param func
   * @param delay
   * @returns
   */
  function debounce<T extends (...args: any[]) => void>(func: T, delay: number) {
    let timeoutId: NodeJS.Timeout;

    return function (this: ThisParameterType<T>, ...args: Parameters<T>) {
      const context = this;

      const later = () => {
        timeoutId = null;
        func.apply(context, args);
      };

      clearTimeout(timeoutId);
      timeoutId = setTimeout(later, delay);
    };
  }

  /**
   * @exports debouncedFunction 修改方法
   */
  const debouncedFunction = debounce((param, row, value, rowIndex) => {
    const steam = {
      creator: 'ERP',
      date: row[value].labelKey.replace(/\-/g, ''),
      maxNums: row.number,
      planNums: param.value,
      process: row.process,
      productionLine: row.productionLine,
      workCenter: row.workCenter,
      workOrderType: row.workOrderType,
      workersNumber: row.workersNumber,
    };
    apiScheduleUpdateSchedulePlanByDate(steam).then((res: any) => {
      if (res.code == '200') {
        notification.info('修改成功');
      } else {
        base.tableData[rowIndex][value].value = null;
        notification.info(res.msg);
      }
    });
  }, 1000);

  watch(
    () => base.pagination,
    () => {
      getTableData();
    },
    {
      deep: true,
    },
  );

  /**
   * @exports viewOptionDetails 查看物料状况
   * @param DB 单别
   * @param DH 单号
   * @param GY 工艺
   * @param SL 数量
   */
  const viewOptionDetails = (DB, DH, GY, SL) => {
    console.log('111');
    const steam = {
      DB: DB,
      DH: DH,
      GY: GY,
      SL: SL,
    };
    scheduleGetMaterialStatus(steam).then((res: any) => {
      console.log(res, '==>steam');
    });
  };
  return {
    base,
    init,
    footerMethod,
    menuConfig,
    contextMenuClickEvent,
    selectAllChangeEvent,
    selectChangeEvent,
    inputTion,
  };
}
